import config from '@/config/index.js'
import { notLoginToast } from './utils.js'
import tools from '@/utils/tools/index.js'

/**
 * @desc 请求
 * @param {string} url 请求地址 
 * @param {obejct} data 请求数据
 * @param {string} method 请求方式
 * @param {obejct} header 请求头信息
 * @returns {Promise<object>}
 */
export default function({ baseURL = config['baseURL'], url, data = {}, method = 'GET', header = {}, defer = false }) {
	return new Promise(async (resolve, reject) => {

		const token = uni.getStorageSync('token');
		token && (header['authorization'] = token);

		uni.request({
			method,
			url: baseURL + url,
			defer: defer,
			data: data,
			dataType: 'json',
			timeout: 1000 * 10,
			header: {
				'content-type': "application/json",
				...header,
			},
			async success(res) {
				const data = res['data'];
				switch (data['code']) {
					case 200:
						resolve(data);
						break;
					case 220:
						uni.hideLoading();
						notLoginToast(data);
						reject(data);
						break;
					default:
						uni.hideLoading();
						tools.toast({ title: data['err'] || '请求失败' });
						reject(data);
				}
			},
			fail(err) {
				uni.showToast({ title: '请求错误！', duration: 1500, icon: 'error' });
				reject({ code: 210, err: '请求失败！' });
			}
		})
	})
}